const { goodsApi } = require('../../services/api')

Page({
  data: {
    title: '', // 商品标题
    price: '', // 商品价格
    description: '', // 商品描述
    images: [], // 商品图片
    category: '', // 商品分类
    location: '', // 交易地点
    categories: ['数码产品', '图书教材', '生活用品', '服装鞋包', '其他'] // 分类选项
  },

  // 选择图片
  chooseImage: function() {
    const that = this
    wx.chooseImage({
      count: 9 - that.data.images.length,
      success: function(res) {
        that.setData({
          images: [...that.data.images, ...res.tempFilePaths]
        })
      }
    })
  },

  // 删除图片
  deleteImage: function(e) {
    const index = e.currentTarget.dataset.index
    const images = this.data.images
    images.splice(index, 1)
    this.setData({ images })
  },

  // 提交表单
  submitForm: async function() {
    if (!this.validateForm()) return
    
    wx.showLoading({
      title: '发布中...'
    })
    
    try {
      // 先上传图片
      const uploadedImages = await this.uploadImages()
      
      // 提交商品信息
      await goodsApi.createGoods({
        title: this.data.title,
        price: this.data.price,
        description: this.data.description,
        images: uploadedImages,
        category: this.data.category,
        location: this.data.location
      })
      
      wx.hideLoading()
      wx.showToast({
        title: '发布成功',
        success: () => {
          wx.navigateBack()
        }
      })
    } catch (err) {
      wx.hideLoading()
      wx.showToast({
        title: err.message,
        icon: 'none'
      })
    }
  },

  // 上传图片
  uploadImages: function() {
    const promises = this.data.images.map(tempFilePath => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: `${currentConfig.apiBaseUrl}/upload`,
          filePath: tempFilePath,
          name: 'file',
          success: res => {
            const data = JSON.parse(res.data)
            resolve(data.url)
          },
          fail: reject
        })
      })
    })
    
    return Promise.all(promises)
  }
  
  // 表单验证
  validateForm: function() {
    const { title, price, description, images, category, location } = this.data
    if (!title.trim()) {
      wx.showToast({ title: '请输入商品标题', icon: 'none' })
      return false
    }
    if (!price.trim()) {
      wx.showToast({ title: '请输入商品价格', icon: 'none' })
      return false
    }
    if (!description.trim()) {
      wx.showToast({ title: '请输入商品描述', icon: 'none' })
      return false
    }
    if (images.length === 0) {
      wx.showToast({ title: '请至少上传一张图片', icon: 'none' })
      return false
    }
    if (!category) {
      wx.showToast({ title: '请选择商品分类', icon: 'none' })
      return false
    }
    if (!location.trim()) {
      wx.showToast({ title: '请输入交易地点', icon: 'none' })
      return false
    }
    return true
  }
})